<template>
  <BasicModal
    v-bind="$attrs"
    :title="props.title"
    :searchInfo="searchInfo"
    width="850px"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <div class="">
      <a-input-search
        v-model:value="value"
        placeholder="请输入"
        style="width: 400px"
        enter-button="搜索"
        @search="onSearch"
      />

      <a-button type="primary" class="mr-2" @click="openModalInformationModal">新增</a-button>
    </div>
    <BasicTable
      @register="registerTable"
      @edit-change="handleEditChange"
      @selection-change="selectionChange"
      :modal="setModalRef"
    >
      <template #default> </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'consigneeAddress'">
          {{
            `${record.consigneeProvince ? record.consigneeProvince : ''}${record.consigneeCity ? record.consigneeCity : ''}${record.consigneeArea ? record.consigneeArea : ''}${record.consigneeAddress}`
          }}
        </template>
        <template v-if="column.key === 'receiverAddress'">
          {{
            `${record.receiverProvince ? record.receiverProvince : ''}${record.receiverCity ? record.receiverCity : ''}${record.receiverArea ? record.receiverArea : ''}${record.receiverAddress}`
          }}
        </template>
        <template v-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <InformationModal
      @register="registerInformationModal"
      @reload="reloadFun"
      :model="modelAddRef"
      :title="`新增${props.title}`"
      :configCode="props.code"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, nextTick, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '@/components/Modal';
  import { BasicTable, useTable, TableAction, ActionItem, EditRecordRow } from '@/components/Table';
  // import { FormSchema } from '/@/components/Form';
  import InformationModal from './addBook/InformationModal.vue';
  import { useMessage } from '@/hooks/web/useMessage';

  // import { getAddressBook } from '@/api/pubInfo/index';

  //  getAddressBook
  // import { useModal } from '@/components/Modal';

  const emit = defineEmits(['success', 'register']);
  const modelAddRef = ref({});
  const props = defineProps({
    code: {
      type: String,
      default: '',
    },
    title: {
      type: String,
      default: '',
    },
    apiTableList: {
      type: Object,
      default: () => {},
    },
    tableColumn: {
      type: Array,
      default: () => [],
    },
    tableType: {
      type: String,
      default: 'checkbox',
    },
  });
  const value = ref<string>('');
  const initIndex = ref(0);
  const setModalRef = ref({});
  const { createMessage } = useMessage();
  const searchInfo = ref({});
  // const editData = reactive({});
  const [registerInformationModal, { openModal: openModalInformationModal }] = useModal();
  // const [registerInformationModal, { openModal: openModal3 }] = useModalInner();
  const [registerModal, { closeModal }] = useModalInner();
  // const [registerInformationModal, { setFieldsValue }] = useForm();setTableData
  const [registerTable, { getDataSource, getSelectRows, reload, clearSelectedRowKeys }] = useTable({
    columns: props.tableColumn,
    showIndexColumn: false,
    api: props.apiTableList.getData,
    beforeFetch: (params) => {
      return { configCode: props.code, data: { keyword: value.value, ...params } };
    },
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    },
    rowSelection: {
      type: props.tableType,
    },
    scroll: { y: '100%' },
    pagination: true,
    showTableSetting: true,
    showSelectionBar: true, // 显示多选状态栏
  });
  // 暴露getDataSource 供父组件使用
  defineExpose({ getDataSource });

  function handleEdit(record: EditRecordRow) {
    console.log(record);
    nextTick(() => {
      openModalInformationModal(true, record);
      modelAddRef.value = record;
    });
  }

  function handleDelete(record: Recordable) {
    clearSelectedRowKeys();
    const deteleAPI = props.apiTableList.delete;
    deteleAPI({ id: record.id }).then((res) => {
      console.log(res);

      createMessage.success('处理成功');
      const searchInfo = unref({ keyword: value.value });
      reload({ searchInfo });
    });
  }

  function reloadFun() {
    reload();
  }
  //勾选

  function selectionChange(e) {
    console.log(e);
  }
  async function onSearch() {
    // getAddressBook(
    //   { configCode: 'eslogis_material' },
    //   { keyword: value.value, current: 1, size: 15 },
    // ).then((res) => {
    //   setModalRef.value = res.records;
    //   setTableData(res.records)
    //   // searchInfo.value = { ...res.records}
    // });
    const searchInfo = unref({ keyword: value.value });
    reload({ searchInfo });
    // reloadFun()
    // console.log('搜索',getRawDataSource({keyword:'12123'}));
    // getRawDataSource({keyword:'12123'})
    // const data =await props.apiTableList.getData
  }

  function handleEditChange(data: Recordable) {
    console.log(data);
  }

  function handleSubmit() {
    console.log(' getSelectRows()()', getSelectRows().length);
    if (getSelectRows().length === 0) return;
    closeModal();
    const dataList = getSelectRows();
    dataList.forEach((item, index) => {
      initIndex.value += 1;
      console.log('initIndex.value', initIndex.value, index);

      item.key = item.key + initIndex.value;
    });
    emit('success', dataList);
    clearSelectedRowKeys();
  }

  // function handleAdd() {
  //   // const data = getDataSource();
  //   // const addRow: EditRecordRow = {
  //   //   name: '',
  //   //   no: '',
  //   //   dept: '',
  //   //   editable: true,
  //   //   isNew: true,
  //   //   key: `${Date.now()}`,
  //   // };
  //   // data.push(addRow);
  // }

  function createActions(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
        },
        {
          label: '删除',
          onClick: handleDelete.bind(null, record),
        },
      ];
    }
  }
</script>
